import 'package:bloc/bloc.dart';
import '../../../base/base_state.dart';
import '../../../models/handle_state.dart';
import '../../../models/response_model.dart';
import '../../../net/http_config.dart';
import '../../../net/ltt_https.dart';
import '../../../widgets/easy_loading.dart';
import '../model/cartoon_model.dart';
import 'event.dart';
import 'state.dart';

class CartoonBloc extends Bloc<BiliNovelEvent, CartoonState> {
  CartoonBloc() : super(CartoonState().init()) {
    on<GetDataEvent>(_initEvent);
  }

  /// 获取数据
  Future<void> _initEvent(event, emit) async {
    XsEasyLoading.showLoading();
    if (event.url == '') {
      XsEasyLoading.dismiss();

      /// 没有更多数据了
      state.isNoMoreDataState = true;
      state.netState = NetState.dataSuccessState;
      emit(state.clone());
      return;
    }
    ResponseModel? responseModel =
        await LttHttp().request<CarDataModel>(event.url, method: HttpConfig.get);
    XsEasyLoading.dismiss();

    Map<String, dynamic> params = event.params;
    int number = params['page'];
    state.isNoMoreDataState = false;
    state.netState = HandleState.handle(responseModel, state, successCode: 0);
    if (state.netState == NetState.dataSuccessState) {
      CarDataModel carDataModel = responseModel.data;
      if (number == 1) {
        state.dataList = carDataModel.feeds;
        if ((state.dataList ?? []).isEmpty) {
          state.netState = NetState.emptyDataState;
        }
      } else {
        state.dataList?.addAll(carDataModel.feeds ?? []);
      }
    }
    emit(state.clone());
  }
}
